package hk.cic.demointegrationapp;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Parcelable;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.cily.utils.log.BaseWv;
import com.cily.utils.log.L;
import com.mfrs.ActionResult;
import com.mfrs.FaceData;
import com.mfrs.HttpU;
import com.mfrs.IFRSMobileService;
import com.mfrs.adapter.RecordBean;
import com.mfrs.demos.EditAc;

import org.apache.commons.io.FileUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import hk.cic.cwrs.bio.integration.log.IBioService;

public class WvAc extends AppCompatActivity {
    private boolean face;

    private BaseWv wv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_wv);

        String s = getSp();
        if (s == null || s.length() < 1){
            App.getApp().showToast("请设置服务器地址");
            return;
        }

        face = getIntent().getBooleanExtra("face", false);

        if (face){
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("ResultLog");
            registerReceiver(resultLogListener, intentFilter);

            IntentFilter ftStatus = new IntentFilter();
            ftStatus.addAction("Status");

            initGPS();

            if (!isSvcConnected) {
                showProgressDialog("正在初始化，请耐心等待...");
                isSvcConnected = connectToFrsMobileService();
                L.i(TAG, "onCreate Connect to FRS Mobile Service: " + String.valueOf(isSvcConnected));
            }

//        }else{
////            initNFC();
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    showNfc();
//                }
//            }, 500);
        }

        try {
//            bindService(new Intent("hk.cic.cwrs.bio.integration.log.IBioService"),
//                    conLog, BIND_AUTO_CREATE);
            bindService(new Intent(this, IBioService.class), conLog, BIND_AUTO_CREATE);
        } catch (Exception e) {
            L.printException(e);
        }


        wv = (BaseWv)findViewById(R.id.wv_id);

        wv.loadUrl("file:///android_asset/InAndOut.html");
        wv.addJsListener(new BaseWv.JsListener() {
            @Override
            public void js4java(String s) {
                loadImg(s);
            }
        });
//
//        findViewById(R.id.btn_id).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                wv.loadUrl("javascript:show()");
//                wv.loadUrl("javascript:popuWorkerInfo('" + 123 + "', '" + 456 + "')" );
//                wv.loadUrl("javascript:popuTableData('0', '9')" );
//            }
//        });
    }

    private void initNFC(){
        mPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        IntentFilter ndef1 = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter ndef2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        mFilters = new IntentFilter[] {
                ndef1,
                //ndef2,
        };

        try {
            ndef1.addDataType("*/*");
            //ndef2.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        mAdapter = NfcAdapter.getDefaultAdapter(this);

        if (getIntent() != null){
            resolveIntent(getIntent());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!face && mAdapter != null) {
            mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
        L.i("Foreground dispatch", "Discovered tag with intent: " + intent);
        resolveIntent(intent);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (!face && mAdapter != null) {
            mAdapter.disableForegroundDispatch(this);
        }
    }
    void resolveIntent(Intent intent) {
        if (face){
            return;
        }

        Context context = getApplicationContext();
        int duration = Toast.LENGTH_LONG;

        // 1) Parse the intent and get the action that triggered this intent
        String action = intent.getAction();
        // 2) Check if it was triggered by a tag discovered interruption.
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
            //  3) Get an instance of the TAG from the NfcAdapter
            Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] extraID = tagFromIntent.getId();

            StringBuilder sb = new StringBuilder();
            for (byte b : extraID) {
                sb.append(String.format("%02X", b));
            };

            String tagID = sb.toString();
            L.e("nfc ID", tagID);

            String name;

            if (tagID.equals("6B9FCB35")){
                name = "David Vassallo";
            }
            else if (tagID.equals("0BCDD135")){
                name = "Kevin Ellul";
            }
            else if (tagID.equals("9B93C435")){
                name = "Guest 013";
            }
            else if (tagID.equals("3B348073")){
                name = "Guest 007";
            } else {
//                name ="Unknown";
                name = tagID;
            }


            Toast toast = Toast.makeText(context, name, duration);
            toast.show();



//            tv_nfc.setText("NFC卡ID：" + tagID);
        };
    }// End of method
    String[][] mTechLists = new String[][] { new String[] { NfcA.class.getName() } };
    Intent intent = getIntent();
    NfcAdapter mAdapter;
    IntentFilter[] mFilters;
    PendingIntent mPendingIntent;

    private void showNfc(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("请刷NFC卡").setTitle("提示");
        builder.setPositiveButton("刷卡", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showAlertDialog(String message, String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle(title);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (face){
            if (bLog == true) {
                unbindService(conLog);
                bLog = false;
            }
        }
    }

    ResultLogListener resultLogListener = new ResultLogListener();

    boolean bLog = false;
    IBioService ibioService = null;

    public class ResultLogListener extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (!face){
                return;
            }

            if (intent.getAction().equals("ResultLog")) {
                intent.getExtras();
                final String strDetail = intent.getStringExtra("resultLog");
//                ICCardResultBean bean = ICCardResultBean.parseJson(strDetail);
//                if (bean != null){
//                    getWorkerDetails(bean.getSessionID(), bean.getCWRNo());
//                }else{
//                    App.getApp().showToast("json解析出错：" + strDetail);
//                }
                if (strDetail == null || strDetail.trim().length() < 1){
                    App.getApp().showToast("监听刷卡失败");
                    return;
                }

                IcCardBean b = JSON.parseObject(strDetail, IcCardBean.class);
                if (b == null || b.getCWRNo() == null || b.getCWRNo().length() < 1){
                    App.getApp().showToast("监听刷卡失败");
                    return;
                }

                if (wv != null) {
                    if (face) {
                        wv.loadUrl("javascript:popuWorkerInfo('" + getSp() + "', '" + b.getCWRNo() + "')");
                    }else {
                        wv.loadUrl("javascript:popuData('" + getSp() + "', '" + b.getCWRNo() + "')");
                    }
                }
                try {
                    if (!bindService(new Intent("hk.cic.cwrs.bio.integration.log.IBioService"),
                            conLog, BIND_AUTO_CREATE)) {
                    }
                } catch (Exception e) {
                    L.printException(e);
                }
                if (bLog) {
                    try {
                        ibioService.ResultLog(strDetail);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private ServiceConnection conLog = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder server) {
            ibioService = IBioService.Stub.asInterface(server);
            bLog = true;
        }

        public void onServiceDisconnected(ComponentName name) {
            bLog = false;
        }
    };

    public String getSp(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("server_host", "");
    }























    private void dialogForPhoto() {
        new AlertDialog.Builder(this).setTitle(R.string.str_title_photo)
                .setMessage(R.string.str_land_screen_for_take_picture)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        toCamera(100);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    private boolean isInit = false;
    private IFRSMobileService frsMobileService;
    private boolean isSvcConnected = false;

    private boolean connectToFrsMobileService() {
        isInit = false;
        Intent serviceIntent = new Intent();
        serviceIntent.setClassName("com.mfrs", "com.mfrs.FRSMobileService");
        isSvcConnected = bindService(serviceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        L.i(TAG, "connectToFrsMobileService: " + String.valueOf(isSvcConnected));

        return isSvcConnected;
    }
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            frsMobileService = IFRSMobileService.Stub.asInterface(service);

//			showAlertDialog(R.string.msg_mfrs_init_ok, R.string.str_init);
            showToast(getString(R.string.msg_mfrs_init_ok));
            Uri imageUri = Uri
                    .fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
            if(imageUri == null){
                hideProDia();
                return;
            }

            File f = new File(imageUri.getPath());
            if(f == null || !f.exists()){
                hideProDia();
            }else{
                handleImage(REQUEST_CODE_FACE_GET, true);
            }

            isInit = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            L.e(TAG, "Service Disconnected.");
        }
    };
    private final String TAG = getClass().getSimpleName();
    private ProgressDialog proDia;
    private void showProgressDialog(String msg){
        proDia = ProgressDialog.show(this, "提示", msg, false, true);
    }
    private void hideProDia(){
        if(proDia != null){
            proDia.dismiss();
        }
    }

    private void loadImg(String url){
        HttpU.load(url, mHandler);
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.obj instanceof Bitmap){
                //照片
                try {
                    saveFile((Bitmap)msg.obj);
                    handleImage(REQUEST_CODE_FACE_GET, false);
                    dialogForPhoto();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    public void saveFile(Bitmap bm) throws IOException {
        File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
        if(!dirFile.exists()){
            dirFile.mkdir();
        }
        File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();
    }

    private void match(int type) {
        if (!isSvcConnected) {
            if (!connectToFrsMobileService()) {
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                return;
            }
        }

        if (!isInit) {
            showAlertDialog(R.string.err_initialization_in_progress, R.string.title_err);
            return;
        }

//		TextView tv = (TextView) findViewById(R.id.labelScoreResult);

        if (faceData1 != null && faceData2 != null) {

            L.i(TAG, "try match");
            float[] score = new float[1];
            score[0] = -1.0f;

            try {
                long time = System.nanoTime();
                ActionResult ar = frsMobileService.faceMatching(faceData1.getFeatureData(), faceData2.getFeatureData(),
                        score);
                time = System.nanoTime() - time;
                // tvTime.setText("faceMatching used time: " +
                // String.valueOf(time));

                if (ar.getCode() == ActionResult.CODE_Success) {
                    Log.i(TAG, "score " + String.valueOf(score[0]));
//					tv.setText(String.valueOf(score[0]));
//					((TextView) findViewById(R.id.textViewError)).setText("");
                    showMatchResult("比对分数：" + String.valueOf(score[0])
                            + "\n比对结果：" + (score[0] >= 0.5 ? "通过" : "不通过"), type, score[0] >= 0.5);

                } else {
                    showAlertDialog(ar);
//					tv.setText("-");
                    L.e(TAG, "Err: " + String.valueOf(ar.getCode()));
                    L.e(TAG, "Err: " + ar.getRemark());
//					((TextView) findViewById(R.id.textViewError))
//							.setText(String.valueOf(ar.getCode()) + " " + ar.getRemark());
                }

            } catch (RemoteException e) {

                L.e(TAG, e.getMessage());
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                isSvcConnected = false;
                e.printStackTrace();
            }
        } else {
//			tv.setText("-");
            Log.e(TAG, "Either FaceData1 or FaceData2 is null");
            if(faceData1 == null){
                showToast("请录入标准人脸");
            }else{
                showToast("请录入待比对的人脸");
            }
        }
    }
    private void showAlertDialog(ActionResult ar) {
        String message = "";
        if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
//			message = "CODE_FaceNotFound: " + ar.getRemark();
            message = "未检测到人脸：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_FRSEngineError) {

//			message = "CODE_FRSEngineError: " + ar.getRemark();
            message = "FRS错误：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_ImageFormatNotSupport) {
//			message = "CODE_ImageFormatNotSupport: " + ar.getRemark();
            message = "图片格式不支持：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData1) {
            message = "CODE_InvalidFeatureData1: " + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_InvalidFeatureData2) {
            message = "CODE_InvalidFeatureData2: " + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_LicenseExpired) {
//			message = "CODE_LicenseExpired: " + ar.getRemark();
            message = "License已过期：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_LicenseNotValid) {
//			message = "CODE_LicenseNotValid: " + ar.getRemark();
            message = "License验证未通过：" + ar.getRemark();
        } else if (ar.getCode() == ActionResult.CODE_UnknownError) {
//			message = "CODE_UnknownError: " + ar.getRemark();
            message = "未知异常：" + ar.getRemark();
        }
        showAlertDialog(message, getResources().getString(R.string.title_err));
    }
    private void showMatchResult(String msg, final int type, final boolean pass){
        new AlertDialog.Builder(this).setTitle("比对结果").setMessage(msg)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        if(pass){

                        }
                    }
                }).create().show();
    }

    private void showToast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void toCamera(int requestCode) {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        String fileName = null;
        if (requestCode == REQUEST_CODE_FACE_GET) {
            fileName = imageNameForFace;
        } else {
            fileName = imageNameForCheck;
        }

        Uri uriImage1 = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + fileName));
        cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uriImage1);
        startActivityForResult(cameraIntent, requestCode);
    }
    private final String imageNameForFace = "image_face_0.jpg";
    private final String imageNameForCheck = "image_face_9.jpg";
    private final int REQUEST_CODE_FACE_GET = 101;
    private com.mfrs.FaceData faceData1;
    private com.mfrs.FaceData faceData2;

    private void showInitFace(){
        if (!isSvcConnected) {
            if (!connectToFrsMobileService()) {
                showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
                return;
            }
        }
        if (!isInit) {
            showAlertDialog(R.string.err_mfrs_not_init, R.string.title_err);
            return;
        }
    }
    private void showAlertDialog(int message, int title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message).setTitle(title);
        AlertDialog dialog = builder.create();
        dialog.show();
    }
    private void handleImage(int imageRequest, boolean loadFaceFromSD) {
        hideProDia();
        Uri imageUri = null;
        if (imageRequest == REQUEST_CODE_FACE_GET) {
            imageUri = Uri
                    .fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/" + imageNameForFace));
            faceData1 = null;
        }

        Bitmap bMap, resizedBitmap, canvasBitmap = null;
        try {
            if (imageUri == null) {
                if(loadFaceFromSD){
                    showToast("请录入标准人脸");
                }else{
                    showToast("人脸图片不存在");
                }
//				showAlertDialog(R.string.err, R.string.title_err);
                L.e(TAG, "ImageUri is null.");
                return;
            }

            File f = new File(imageUri.getPath());
            if (!f.exists()) {
                showAlertDialog("File does not exist! " + f.toString(), getResources().getString(R.string.title_err));
                L.e(TAG, "File does not exist!" + f.toString());
                return;
            }

            byte[] image = FileUtils.readFileToByteArray(f);
            int imageSize = image.length / 1024;
            L.i(TAG, String.format("Image size before resizing: %d", imageSize));

            bMap = BitmapFactory.decodeByteArray(image, 0, image.length);

            if (bMap == null) {
                showAlertDialog(R.string.err_imagefile, R.string.title_err);
                L.e(TAG, "File does not exist!" + f.toString());
                return;
            }

            L.i(TAG, String.format("Current width * height: %d x %d ", bMap.getWidth(), bMap.getHeight()));

            Dimension imgDimension = new Dimension(bMap.getWidth(), bMap.getHeight());
            Dimension boundaryHorizontalDimension = new Dimension(com.mfrs.demos.MainActivity.MAX_WIDTH, com.mfrs.demos.MainActivity.MAX_HEIGHT);
            Dimension boundaryVerticalDimension = new Dimension(com.mfrs.demos.MainActivity.MAX_HEIGHT, com.mfrs.demos.MainActivity.MAX_WIDTH);
            L.i(TAG, String.format("Img Resolution before resizing: %d x %d", imgDimension.getWidth(),
                    imgDimension.getHeight()));

            Dimension newDimension = imgDimension;
            Boolean resized = false;
            resizedBitmap = bMap;

            if (bMap.getWidth() > bMap.getHeight()) {
                if (bMap.getWidth() > com.mfrs.demos.MainActivity.MAX_WIDTH || bMap.getHeight() > com.mfrs.demos.MainActivity.MAX_HEIGHT) {
                    L.i(TAG, String.format("Img Boundary: %d x %d", boundaryHorizontalDimension.getWidth(),
                            boundaryHorizontalDimension.getHeight()));
                    newDimension = getScaledDimension(newDimension, boundaryHorizontalDimension);
                    resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),
                            false);
                    resized = true;
                }
            } else {
                L.i(TAG, "width < height");
                if (bMap.getWidth() > com.mfrs.demos.MainActivity.MAX_HEIGHT || bMap.getHeight() > com.mfrs.demos.MainActivity.MAX_WIDTH) {
                    L.i(TAG, String.format("Img Boundary: %d x %d", boundaryVerticalDimension.getWidth(),
                            boundaryVerticalDimension.getHeight()));
                    newDimension = getScaledDimension(newDimension, boundaryVerticalDimension);
                    resizedBitmap = Bitmap.createScaledBitmap(bMap, newDimension.getWidth(), newDimension.getHeight(),
                            false);
                    resized = true;
                }
            }

            L.i(TAG, String.format("Img Resolution after resizing: %d x %d", resizedBitmap.getWidth(),
                    resizedBitmap.getHeight()));

            ArrayList<FaceData> fdList = new ArrayList<FaceData>();
            ActionResult ar = null;

            if (resized) {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
                byte[] resizedImageByte = stream.toByteArray();
                int size = resizedImageByte.length / 1024;
                L.i(TAG, "Size after resizing: " + resizedImageByte.length / 1024 + "KB");

                if (size < 800) {
                    // imgView.setImageBitmap(resizedBitmap);
//					img_avatar.setImageBitmap(resizedBitmap);
                    long time = System.nanoTime();
                    ar = frsMobileService.faceDataDetection(resizedImageByte, fdList);
                    time = System.nanoTime() - time;
                    // tvTime.setText("faceDataDetection used time:
                    // " + String.valueOf(time));
                } else {
                    showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                    L.e(TAG, "Please keep image less than 800KB after compression");
                }

                resizedImageByte = null;
            } else {
                try {
                    if (image.length / 1024 < 1000) {
                        // imgView.setImageBitmap(resizedBitmap);
//						img_avatar.setImageBitmap(resizedBitmap);
                        L.i(TAG, "Before faceDataDetection");
                        long time = System.nanoTime();
                        ar = frsMobileService.faceDataDetection(image, fdList);
                        time = System.nanoTime() - time;
                        // tvTime.setText("faceDataDetection used
                        // time: " + String.valueOf(time));
                        L.i(TAG, "After faceDataDetection");
                    } else {
                        showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                        L.e(TAG, "Image Size exceeds 1MB after compression");
                    }

                } catch (Exception e) {
                    L.e(TAG, "Error in FaceDataDetection");
                }

            }

            if (ar == null) {
                showAlertDialog(R.string.err, R.string.title_err);
                L.e(TAG, "Action Result is null");
                return;
            }

            if (ar.getCode() != ActionResult.CODE_Success) {
//				showAlertDialog(ar);

                if (ar.getCode() == ActionResult.CODE_FaceNotFound) {
                    // isFaceFoundTextView.setText("Face Found:
                    // No");
                    // faceQualityScoreTextView.setText("Face
                    // Quality: -");
                    // errTextView.setText("Face Not Found");
                    showFaceQualityDialog(RESULT_ERROR, imageRequest, "未检测到人脸");
                } else {
                    // isFaceFoundTextView.setText("Face Found:
                    // Err");
                    // faceQualityScoreTextView.setText("Face
                    // Quality: Err");
                    // errTextView.setText(String.valueOf(ar.getCode())
                    // + ": " + ar.getRemark());
                    showFaceQualityDialog(RESULT_ERROR, imageRequest, "人脸质量不佳");
                }
                return;
            }

            if (fdList.size() > 0) {
                // highlight the head and eyes positions
                L.i(TAG, String.format("Feature Data List Size: %d", fdList.size()));

                Bitmap copiedImage = resizedBitmap.copy(Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(copiedImage);

                try {
                    canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
                            Bitmap.Config.ARGB_8888);
                } catch (OutOfMemoryError e) {
                    while (canvasBitmap == null) {
                        System.gc();
                        System.runFinalization();
                        L.i(TAG, "Draw On Image: Create Bitmap out Of Memory Error.\nCreate again now.");
                        canvasBitmap = Bitmap.createBitmap(resizedBitmap.getWidth(), resizedBitmap.getHeight(),
                                Bitmap.Config.ARGB_8888);
                    }
                }

                for (int i = 0; i < fdList.size(); i++) {
                    int[] headArray = fdList.get(i).getHead();
                    int[] leftEyeArray = fdList.get(i).getLeftEye();
                    int[] rightEyeArray = fdList.get(i).getRightEye();

                    if (headArray != null && leftEyeArray != null && rightEyeArray != null) {
                        try {
                            String rectString = String.format("New head in Main: left %d, top %d, right %d, bottom %d",
                                    headArray[0], headArray[1], headArray[2], headArray[3]);
                            L.i(TAG, rectString);

                            Paint rectpaint = new Paint();
                            rectpaint.setStyle(Paint.Style.STROKE);
                            rectpaint.setColor(Color.GREEN);
                            rectpaint.setStrokeWidth(7);
                            float leftx = headArray[0];
                            float topy = headArray[1];
                            float rightx = headArray[2];
                            float bottomy = headArray[3];

                            Paint cirpaint = new Paint();
                            cirpaint.setStyle(Paint.Style.STROKE);
                            cirpaint.setColor(Color.GREEN);
                            cirpaint.setStrokeWidth(5);

                            if (i == 0) {
                                rectpaint.setColor(Color.CYAN);

                                cirpaint.setColor(Color.CYAN);
                            }

                            canvas.drawRect(leftx, topy, rightx, bottomy, rectpaint);
                            canvas.drawCircle(leftEyeArray[0], leftEyeArray[1], 10, cirpaint);
                            canvas.drawCircle(rightEyeArray[0], rightEyeArray[1], 10, cirpaint);

                        } catch (Exception e) {
                            L.e(TAG, "Exception encountered in drawing Image");
                            showAlertDialog(R.string.error_mfrs_draw_image, R.string.title_err);
                            // imgView.setImageBitmap(resizedBitmap);
//							img_avatar.setImageBitmap(resizedBitmap);
                        }

                    } else {
                        L.e(TAG, "HeadArray or EyeArray is null");
                        showAlertDialog(R.string.error_headeye_notok, R.string.title_err);
                        // imgView.setImageBitmap(resizedBitmap);
//						img_avatar.setImageBitmap(resizedBitmap);
                    }
                }

                // imgView.setImageBitmap(copiedImage);
                if(imageRequest == REQUEST_CODE_FACE_GET){
//                    img_avatar.setImageBitmap(copiedImage);
                }

            } else {
                L.e(TAG, "Cannot find feature data");
            }

            if (fdList.size() > 0) {
                // isFaceFoundTextView.setText("Face Found:
                // Yes");
                // faceQualityScoreTextView.setText(
                // "Face Quality:" +
                // String.valueOf(fdList.get(0).getFaceQualityScore()));

                if(!loadFaceFromSD){
                    showFaceQualityDialog(RESULT_SUCCESS, imageRequest,
                            "分数：" + fdList.get(0).getFaceQualityScore());
                }
                if (imageRequest == REQUEST_CODE_FACE_GET) {
                    faceData1 = fdList.get(0);

                    L.i(TAG, "set faceData1");
                }
                // errTextView.setText("");
            }

            resizedBitmap = null;
            bMap = null;
            canvasBitmap = null;

        } catch (IOException e) {
            showAlertDialog(e.getMessage(), getResources().getString(R.string.title_err));
            e.printStackTrace();
        } catch (RemoteException e) {
            showAlertDialog(R.string.err_mfrs_not_found, R.string.title_err);
            isSvcConnected = false;
            e.printStackTrace();
        } catch (Exception e) {
            showAlertDialog(e.getMessage(), "ERROR");
            e.printStackTrace();
        }
    }
    private final int RESULT_SUCCESS = 0, RESULT_ERROR = -1;
    private void showFaceQualityDialog(final int result, final int type, String msg){
        String ok = "确定";
        if(result == RESULT_SUCCESS){

        }else{
            ok = "重拍";
        }

        new AlertDialog.Builder(this).setTitle("人脸检测")
                .setMessage(msg)
                .setPositiveButton(ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if(result == RESULT_SUCCESS){
                            if(type == 100){

                            }
                        }else{
                            toCamera(type);
                        }
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
                .create().show();
    }
    private class Dimension {
        private final int width;
        private final int height;

        public Dimension(int width, int height) {
            this.width = width;
            this.height = height;
        }

        public int getWidth() {
            return this.width;
        }

        public int getHeight() {
            return this.height;

        }
    }
    public Dimension getScaledDimension(Dimension imgSize, Dimension boundary) {
        int original_width = imgSize.width;
        int original_height = imgSize.height;
        int bound_width = boundary.width;
        int bound_height = boundary.height;
        int new_width = original_width;
        int new_height = original_height;

        // first check if we need to scale width
        if (original_width > bound_width) {
            // scale width to fit
            new_width = bound_width;
            // scale height to maintain aspect ratio
            new_height = (new_width * original_height) / original_width;
        }

        // then check if we need to scale even with the new height
        if (new_height > bound_height) {
            // scale height to fit instead
            new_height = bound_height;
            // scale width to maintain aspect ratio
            new_width = (new_height * original_width) / original_height;
        }

        return new Dimension(new_width, new_height);
    }
























    private String gps;

    private LocationClient locationClient = null;
    private static final int UPDATE_TIME = 5000;
    private static int LOCATION_COUTNS = 0;

    private void initGPS(){
        locationClient = new LocationClient(this);
        //设置定位条件
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);        //是否打开GPS
        option.setCoorType("bd09ll");       //设置返回值的坐标类型。
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置定位优先级
        option.setProdName("LocationDemo"); //设置产品线名称。强烈建议您使用自定义的产品线名称，方便我们以后为您提供更高效准确的定位服务。
        option.setScanSpan(UPDATE_TIME);    //设置定时定位的时间间隔。单位毫秒
        locationClient.setLocOption(option);

        //注册位置监听器
        locationClient.registerLocationListener(new BDLocationListener() {

            @Override
            public void onReceiveLocation(BDLocation location) {
                // TODO Auto-generated method stub
                if (location == null) {
                    return;
                }
                StringBuffer sb = new StringBuffer(256);
//                sb.append("Time : ");
//                sb.append(location.getTime());
//                sb.append("\nError code : ");
                sb.append(location.getLocType());
                sb.append("\nLatitude : ");
                sb.append(location.getLatitude());
                sb.append("\nLontitude : ");

                gps = location.getLatitude() + "," + location.getLongitude();

                sb.append(location.getLongitude());
//                sb.append("\nRadius : ");
//                sb.append(location.getRadius());
//                if (location.getLocType() == BDLocation.TypeGpsLocation){
//                    sb.append("\nSpeed : ");
//                    sb.append(location.getSpeed());
//                    sb.append("\nSatellite : ");
//                    sb.append(location.getSatelliteNumber());
//                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){
//                    sb.append("\nAddress : ");
//                    sb.append(location.getAddrStr());
//                }
                LOCATION_COUTNS ++;
//                sb.append("\n检查位置更新次数：");
//                sb.append(String.valueOf(LOCATION_COUTNS));

            }

            @Override
            public void onReceivePoi(BDLocation bdLocation) {

            }
        });


    }







    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            showToast("已取消");
            return;
        }
        if (requestCode == REQUEST_CODE_FACE_GET) {
            handleImage(REQUEST_CODE_FACE_GET, false);
        } else if (requestCode == 100) {
            handleImage(100, false);
        }

    }
}